﻿package com.kun.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class EmailAction extends ActionSupport{

	private static final long serialVersionUID = 1L;
	
	private String emailAddr;
	
	public void sendCode(){
		String codeNum = getRandNum(6);
		ServletActionContext.getRequest().getSession()
							.setAttribute("codeNum",codeNum);
		//发送邮件
		  // 设置邮件服务器信息
		  MailSenderInfo mailInfo = new MailSenderInfo();
		  mailInfo.setMailServerHost("smtp.163.com");
		  mailInfo.setMailServerPort("25");
		  mailInfo.setValidate(true);
		  // 邮箱用户名
		  mailInfo.setUserName("XXXXX@163.com");
		  // 邮箱密码
		  mailInfo.setPassword("XXXXe");
		  // 发件人邮箱
		  mailInfo.setFromAddress("XXXXXl@163.com");
		  // 收件人邮箱
		  mailInfo.setToAddress(emailAddr);
		  // 邮件标题
		  mailInfo.setSubject("XXXX");
		  // 邮件内容
		  StringBuffer buffer = new StringBuffer();
		  //发送生成的验证码
		  buffer.append(codeNum);
		  mailInfo.setContent(buffer.toString());
		  // 发送邮件
		  SimpleMailSender sms = new SimpleMailSender();
		  // 发送文体格式
		  boolean flag = sms.sendTextMail(mailInfo);
		  if(flag){
			  System.out.println("邮件发送完毕");			  
		  }else{
			  System.out.println("邮件发送失败");			  			  
		  }
		
		
	}
	/**
	 * 获取一个charCount位的数字字符串
	 * @param charCount 多少位
	 * @return
	 */
	public String getRandNum(int charCount) {
        String charValue = "";
        for (int i = 0; i < charCount; i++) {
            char c = (char) (randomInt(0, 10) + '0');
            charValue += String.valueOf(c);
        }
        return charValue;
    }
	/**
	 * 获取数字
	 * @param from 从多少开始
	 * @param to 到多少结束
	 * @return 返回数字
	 */
	public int randomInt(int from, int to) {
        Random r = new Random();
        return from + r.nextInt(to - from);
    }
	
	private String returnNum;
	
	public void ckCode(){
		String cNum = (String) ServletActionContext.getRequest().getSession()
			.getAttribute("codeNum");
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("UTF-8");
		//获得输出流
		PrintWriter pw;
		try {
			pw = response.getWriter();
			//将数据写入输出流
			if(returnNum.equals(cNum)){
				pw.write("1");
			}else{
				pw.print("0");
			}
			//清楚数据流缓冲区
			pw.flush();
			//关闭输出流
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String getEmailAddr() {
		return emailAddr;
	}
	public void setEmailAddr(String emailAddr) {
		this.emailAddr = emailAddr;
	}
	public String getReturnNum() {
		return returnNum;
	}
	public void setReturnNum(String returnNum) {
		this.returnNum = returnNum;
	}
}
